package com.supermarket.ui;

import com.supermarket.model.User;
import com.supermarket.model.Product;
import com.supermarket.model.SalesOrder;
import com.supermarket.model.ExpiringProduct;
import com.supermarket.model.SalesDetail;
import com.supermarket.dao.ProductDAO;
import com.supermarket.dao.SalesDAO;
import com.supermarket.dao.ExpiringProductDAO;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.math.BigDecimal;
import java.sql.Date;
import java.sql.Time;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import javax.swing.Timer;

/**
 * 收银员主界面
 * 提供商品销售、临期商品申报、个人销售查询等功能
 */
public class CashierMainFrame extends JFrame {

    private User currentUser;
    private ProductDAO productDAO;
    private SalesDAO salesDAO;
    private ExpiringProductDAO expiringProductDAO;

    // 主面板
    private JTabbedPane tabbedPane;
    private JLabel statusLabel;
    private JLabel userInfoLabel;

    // 销售收银面板
    private JTextField productCodeField;
    private JTextField quantityField;
    private JComboBox<String> paymentMethodComboBox;
    private JButton addToCartButton, searchProductButton, completeOrderButton, cancelOrderButton;
    private JTable cartTable;
    private DefaultTableModel cartTableModel;
    private JLabel totalAmountLabel, discountLabel, finalAmountLabel;
    private List<CartItem> cartItems;

    // 商品查询面板
    private JTable productQueryTable;
    private DefaultTableModel productQueryTableModel;
    private JTextField productSearchField;
    private JButton productSearchButton;

    // 个人销售统计面板
    private JTable personalSalesTable;
    private DefaultTableModel personalSalesTableModel;
    private JComboBox<String> personalPeriodComboBox;
    private JButton personalQueryButton;
    private JLabel personalTotalLabel;

    // 临期商品申报面板
    private JTable expiringProductsTable;
    private DefaultTableModel expiringProductsTableModel;
    private JButton declareExpiringButton;
    private JComboBox<String> expiryStatusFilterComboBox;
    private JTextField expiringProductSearchField;
    private JTextArea productDetailsArea;

    // 搜索和筛选相关
    private Timer searchTimer; // 防抖动处理
    private List<Product> allExpiringProducts; // 存储所有商品数据
    private List<Product> filteredProducts; // 存储筛选后的商品数据

    public CashierMainFrame(User user) {
        this.currentUser = user;
        this.productDAO = new ProductDAO();
        this.salesDAO = new SalesDAO();
        this.expiringProductDAO = new ExpiringProductDAO();

        initializeComponents();
        setupLayout();
        setupEventListeners();
        setFrameProperties();
        loadInitialData();
    }

    /**
     * 初始化组件
     */
    private void initializeComponents() {
        // 创建现代化选项卡面板
        tabbedPane = new JTabbedPane();
        tabbedPane.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        tabbedPane.setBackground(Color.WHITE);
        tabbedPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 状态栏
        statusLabel = new JLabel("系统就绪");
        statusLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));
        statusLabel.setForeground(new Color(108, 117, 125));

        userInfoLabel = new JLabel("当前用户：" + currentUser.getRealName() + " (" + currentUser.getRoleName() + ")");
        userInfoLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));
        userInfoLabel.setForeground(new Color(52, 58, 64));

        // 初始化购物车
        cartItems = new ArrayList<>();

        // 初始化各个功能面板
        initSalesPanel();
        initProductQueryPanel();
        initPersonalSalesPanel();
        initExpiringProductsPanel();
    }

    /**
     * 初始化销售收银面板
     */
    private void initSalesPanel() {
        JPanel salesPanel = new JPanel(new BorderLayout());
        salesPanel.setBackground(Color.WHITE);
        salesPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));

        // 左侧：商品输入和购物车
        JPanel leftPanel = createStyledPanel();
        leftPanel.setLayout(new BorderLayout(10, 10));
        leftPanel.setPreferredSize(new Dimension(500, 0));

        // 商品输入面板
        JPanel inputPanel = createStyledPanel();
        inputPanel.setLayout(new GridBagLayout());
        inputPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createTitledBorder(
                        BorderFactory.createLineBorder(new Color(220, 220, 220)),
                        "商品录入",
                        0, 0,
                        new Font("Microsoft YaHei", Font.BOLD, 14),
                        new Color(52, 58, 64)),
                BorderFactory.createEmptyBorder(15, 15, 15, 15)));

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10);
        gbc.anchor = GridBagConstraints.WEST;

        // 商品编码
        gbc.gridx = 0;
        gbc.gridy = 0;
        JLabel codeLabel = new JLabel("商品编码：");
        codeLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        codeLabel.setForeground(new Color(73, 80, 87));
        inputPanel.add(codeLabel, gbc);

        gbc.gridx = 1;
        productCodeField = new JTextField();
        productCodeField.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        productCodeField.setBorder(createModernBorder());
        productCodeField.setPreferredSize(new Dimension(200, 35));
        inputPanel.add(productCodeField, gbc);

        gbc.gridx = 2;
        searchProductButton = createStyledButton("查找", new Color(74, 144, 226));
        inputPanel.add(searchProductButton, gbc);

        // 销售数量
        gbc.gridx = 0;
        gbc.gridy = 1;
        JLabel quantityLabel = new JLabel("销售数量：");
        quantityLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        quantityLabel.setForeground(new Color(73, 80, 87));
        inputPanel.add(quantityLabel, gbc);

        gbc.gridx = 1;
        quantityField = new JTextField("1");
        quantityField.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        quantityField.setBorder(createModernBorder());
        quantityField.setPreferredSize(new Dimension(200, 35));
        inputPanel.add(quantityField, gbc);

        gbc.gridx = 2;
        addToCartButton = createStyledButton("加入购物车", new Color(40, 167, 69));
        inputPanel.add(addToCartButton, gbc);

        // 支付方式
        gbc.gridx = 0;
        gbc.gridy = 2;
        JLabel paymentLabel = new JLabel("支付方式：");
        paymentLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        paymentLabel.setForeground(new Color(73, 80, 87));
        inputPanel.add(paymentLabel, gbc);

        gbc.gridx = 1;
        paymentMethodComboBox = new JComboBox<>(new String[] { "现金", "刷卡", "移动支付" });
        paymentMethodComboBox.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        paymentMethodComboBox.setPreferredSize(new Dimension(200, 35));
        inputPanel.add(paymentMethodComboBox, gbc);

        // 购物车表格
        String[] cartColumns = { "商品编码", "商品名称", "单价", "数量", "小计", "操作" };
        cartTableModel = new DefaultTableModel(cartColumns, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return column == 3; // 只有数量列可编辑
            }
        };
        cartTable = createStyledTable(cartTableModel);

        // 添加数量修改监听器
        cartTable.getModel().addTableModelListener(e -> {
            if (e.getColumn() == 3) { // 数量列
                updateCartItemQuantity(e.getFirstRow());
            }
        });

        JScrollPane cartScrollPane = new JScrollPane(cartTable);
        cartScrollPane.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createTitledBorder(
                        BorderFactory.createLineBorder(new Color(220, 220, 220)),
                        "购物车",
                        0, 0,
                        new Font("Microsoft YaHei", Font.BOLD, 14),
                        new Color(52, 58, 64)),
                BorderFactory.createEmptyBorder(10, 10, 10, 10)));
        cartScrollPane.setPreferredSize(new Dimension(0, 300));
        cartScrollPane.getViewport().setBackground(Color.WHITE);

        leftPanel.add(inputPanel, BorderLayout.NORTH);
        leftPanel.add(cartScrollPane, BorderLayout.CENTER);

        // 右侧：结算面板
        JPanel rightPanel = createStyledPanel();
        rightPanel.setLayout(new BorderLayout(10, 10));
        rightPanel.setPreferredSize(new Dimension(300, 0));

        // 结算信息
        JPanel checkoutPanel = createStyledPanel();
        checkoutPanel.setLayout(new BoxLayout(checkoutPanel, BoxLayout.Y_AXIS));
        checkoutPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createTitledBorder(
                        BorderFactory.createLineBorder(new Color(220, 220, 220)),
                        "结算信息",
                        0, 0,
                        new Font("Microsoft YaHei", Font.BOLD, 14),
                        new Color(52, 58, 64)),
                BorderFactory.createEmptyBorder(20, 20, 20, 20)));

        totalAmountLabel = new JLabel("商品总额: ¥0.00");
        totalAmountLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 16));
        totalAmountLabel.setForeground(new Color(52, 58, 64));
        totalAmountLabel.setAlignmentX(Component.LEFT_ALIGNMENT);

        discountLabel = new JLabel("折扣金额: ¥0.00");
        discountLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 16));
        discountLabel.setForeground(new Color(108, 117, 125));
        discountLabel.setAlignmentX(Component.LEFT_ALIGNMENT);

        finalAmountLabel = new JLabel("应收金额: ¥0.00");
        finalAmountLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 20));
        finalAmountLabel.setForeground(new Color(220, 53, 69));
        finalAmountLabel.setAlignmentX(Component.LEFT_ALIGNMENT);

        checkoutPanel.add(totalAmountLabel);
        checkoutPanel.add(Box.createVerticalStrut(15));
        checkoutPanel.add(discountLabel);
        checkoutPanel.add(Box.createVerticalStrut(15));
        checkoutPanel.add(finalAmountLabel);

        // 操作按钮
        JPanel buttonPanel = createStyledPanel();
        buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS));
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(20, 0, 0, 0));

        completeOrderButton = createStyledButton("完成订单", new Color(40, 167, 69));
        completeOrderButton.setFont(new Font("Microsoft YaHei", Font.BOLD, 16));
        completeOrderButton.setAlignmentX(Component.CENTER_ALIGNMENT);
        completeOrderButton.setMaximumSize(new Dimension(Integer.MAX_VALUE, 50));

        cancelOrderButton = createStyledButton("取消订单", new Color(220, 53, 69));
        cancelOrderButton.setAlignmentX(Component.CENTER_ALIGNMENT);
        cancelOrderButton.setMaximumSize(new Dimension(Integer.MAX_VALUE, 40));

        JButton clearCartButton = createStyledButton("清空购物车", new Color(255, 193, 7));
        clearCartButton.setAlignmentX(Component.CENTER_ALIGNMENT);
        clearCartButton.setMaximumSize(new Dimension(Integer.MAX_VALUE, 40));

        buttonPanel.add(completeOrderButton);
        buttonPanel.add(Box.createVerticalStrut(10));
        buttonPanel.add(cancelOrderButton);
        buttonPanel.add(Box.createVerticalStrut(10));
        buttonPanel.add(clearCartButton);

        rightPanel.add(checkoutPanel, BorderLayout.CENTER);
        rightPanel.add(buttonPanel, BorderLayout.SOUTH);

        // 设置事件监听器
        setupSalesEventListeners(clearCartButton);

        // 组装销售面板
        salesPanel.add(leftPanel, BorderLayout.CENTER);
        salesPanel.add(rightPanel, BorderLayout.EAST);

        tabbedPane.addTab("收银台", salesPanel);
    }

    /**
     * 初始化商品查询面板
     */
    private void initProductQueryPanel() {
        JPanel queryPanel = new JPanel(new BorderLayout());
        queryPanel.setBackground(Color.WHITE);
        queryPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));

        // 查询条件面板 - 优化设计
        JPanel searchPanel = createStyledPanel();
        searchPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 15, 10));
        searchPanel.setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 5));

        JLabel searchLabel = new JLabel("🔍 商品查询：");
        searchLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 14));
        searchLabel.setForeground(new Color(73, 80, 87));

        productSearchField = new JTextField();
        productSearchField.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        productSearchField.setBorder(createModernBorder());
        productSearchField.setPreferredSize(new Dimension(280, 36));

        // 添加占位符提示
        productSearchField.setToolTipText("输入商品名称或编码进行搜索，留空显示全部商品");

        productSearchButton = createStyledButton("搜索", new Color(74, 144, 226));
        JButton showAllButton = createStyledButton("显示全部", new Color(40, 167, 69));
        JButton refreshButton = createStyledButton("刷新", new Color(108, 117, 125));

        searchPanel.add(searchLabel);
        searchPanel.add(productSearchField);
        searchPanel.add(productSearchButton);
        searchPanel.add(showAllButton);
        searchPanel.add(refreshButton);

        // 添加按钮事件监听器
        showAllButton.addActionListener(event -> {
            productSearchField.setText(""); // 清空搜索框
            loadAllProducts(); // 显示全部商品
        });

        refreshButton.addActionListener(event -> {
            loadAllProducts(); // 刷新商品列表
            productSearchField.setText("");
        });

        // 商品信息表格
        String[] productColumns = { "商品编码", "商品名称", "类别", "单位", "售价", "库存", "库存状态" };
        productQueryTableModel = new DefaultTableModel(productColumns, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        productQueryTable = createStyledTable(productQueryTableModel);

        JScrollPane queryScrollPane = new JScrollPane(productQueryTable);
        queryScrollPane.setBorder(BorderFactory.createLineBorder(new Color(220, 220, 220)));
        queryScrollPane.getViewport().setBackground(Color.WHITE);

        queryPanel.add(searchPanel, BorderLayout.NORTH);
        queryPanel.add(queryScrollPane, BorderLayout.CENTER);

        tabbedPane.addTab("商品查询", queryPanel);
    }

    /**
     * 初始化个人销售统计面板
     */
    private void initPersonalSalesPanel() {
        JPanel personalSalesPanel = new JPanel(new BorderLayout());
        personalSalesPanel.setBackground(Color.WHITE);
        personalSalesPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));

        // 查询面板
        JPanel queryPanel = createStyledPanel();
        queryPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));

        JLabel periodLabel = new JLabel("统计周期：");
        periodLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        periodLabel.setForeground(new Color(73, 80, 87));

        personalPeriodComboBox = new JComboBox<>(new String[] { "今日", "本周", "本月" });
        personalPeriodComboBox.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        personalPeriodComboBox.setPreferredSize(new Dimension(120, 35));

        personalQueryButton = createStyledButton("查询统计", new Color(74, 144, 226));

        personalTotalLabel = new JLabel("个人销售总额: ¥0.00");
        personalTotalLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 16));
        personalTotalLabel.setForeground(new Color(220, 53, 69));

        queryPanel.add(periodLabel);
        queryPanel.add(personalPeriodComboBox);
        queryPanel.add(personalQueryButton);
        queryPanel.add(Box.createHorizontalStrut(50));
        queryPanel.add(personalTotalLabel);

        // 个人销售统计表格
        String[] personalSalesColumns = { "订单编号", "订单时间", "商品数量", "订单金额", "支付方式", "状态" };
        personalSalesTableModel = new DefaultTableModel(personalSalesColumns, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        personalSalesTable = createStyledTable(personalSalesTableModel);

        JScrollPane personalScrollPane = new JScrollPane(personalSalesTable);
        personalScrollPane.setBorder(BorderFactory.createLineBorder(new Color(220, 220, 220)));
        personalScrollPane.getViewport().setBackground(Color.WHITE);

        personalSalesPanel.add(queryPanel, BorderLayout.NORTH);
        personalSalesPanel.add(personalScrollPane, BorderLayout.CENTER);

        tabbedPane.addTab("个人销售", personalSalesPanel);
    }

    /**
     * 初始化临期商品申报面板
     */
    private void initExpiringProductsPanel() {
        JPanel expiringPanel = new JPanel(new BorderLayout());
        expiringPanel.setBackground(Color.WHITE);
        expiringPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));

        // 顶部面板：包含筛选、搜索和操作按钮
        JPanel topPanel = createStyledPanel();
        topPanel.setLayout(new BorderLayout(10, 10));

        // 筛选和搜索面板
        JPanel filterSearchPanel = createStyledPanel();
        filterSearchPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 15, 10));
        filterSearchPanel.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0));

        // 过期状态筛选下拉框
        JLabel filterLabel = new JLabel("🔍 过期状态：");
        filterLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 14));
        filterLabel.setForeground(new Color(73, 80, 87));

        expiryStatusFilterComboBox = new JComboBox<>(new String[] {
                "全部状态", "已过期", "即将过期", "临期商品", "即将临期", "正常", "信息不完整"
        });
        expiryStatusFilterComboBox.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        expiryStatusFilterComboBox.setPreferredSize(new Dimension(140, 36));

        // 实时搜索输入框
        JLabel searchLabel = new JLabel("商品搜索：");
        searchLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 14));
        searchLabel.setForeground(new Color(73, 80, 87));

        expiringProductSearchField = new JTextField();
        expiringProductSearchField.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        expiringProductSearchField.setBorder(createModernBorder());
        expiringProductSearchField.setPreferredSize(new Dimension(280, 36));
        expiringProductSearchField.setToolTipText("输入商品名称或编码进行搜索");

        // 筛选条件清除按钮
        JButton clearFiltersButton = createStyledButton("清除筛选", new Color(108, 117, 125));

        filterSearchPanel.add(filterLabel);
        filterSearchPanel.add(expiryStatusFilterComboBox);
        filterSearchPanel.add(Box.createHorizontalStrut(20));
        filterSearchPanel.add(searchLabel);
        filterSearchPanel.add(expiringProductSearchField);
        filterSearchPanel.add(clearFiltersButton);

        // 操作面板
        JPanel operationPanel = createStyledPanel();
        operationPanel.setLayout(new FlowLayout(FlowLayout.RIGHT, 10, 10));

        declareExpiringButton = createStyledButton("申报临期商品", new Color(255, 193, 7));
        JButton refreshExpiringButton = createStyledButton("刷新列表", new Color(108, 117, 125));

        operationPanel.add(declareExpiringButton);
        operationPanel.add(refreshExpiringButton);

        // 组装顶部面板
        topPanel.add(filterSearchPanel, BorderLayout.CENTER);
        topPanel.add(operationPanel, BorderLayout.EAST);

        // 添加事件监听器
        refreshExpiringButton.addActionListener(event -> loadAllProductsWithExpiryInfo());
        clearFiltersButton.addActionListener(event -> clearFiltersAndSearch());

        // 更新表格列定义，包含所有需要的商品信息字段
        String[] expiringColumns = {
                "商品编码", "商品名称", "类别", "供应商", "出厂日期",
                "保质期(天)", "过期日期", "剩余天数", "库存数量", "过期状态"
        };
        expiringProductsTableModel = new DefaultTableModel(expiringColumns, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        expiringProductsTable = createStyledTable(expiringProductsTableModel);

        // 增强表格行颜色编码，根据过期状态设置不同背景色，并实现搜索结果高亮显示
        expiringProductsTable.setDefaultRenderer(Object.class, new javax.swing.table.DefaultTableCellRenderer() {
            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                    boolean hasFocus, int row, int column) {
                Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

                if (!isSelected) {
                    try {
                        // 获取过期状态列的值
                        Object statusObj = table.getValueAt(row, 9); // 过期状态列
                        if (statusObj != null) {
                            String status = statusObj.toString();

                            switch (status) {
                                case "已过期":
                                    c.setBackground(new Color(255, 235, 238)); // 红色背景 #ffebee
                                    c.setForeground(new Color(220, 53, 69));
                                    break;
                                case "即将过期":
                                    c.setBackground(new Color(255, 243, 224)); // 橙色背景 #fff3e0
                                    c.setForeground(new Color(255, 152, 0));
                                    break;
                                case "临期商品":
                                    c.setBackground(new Color(255, 253, 231)); // 黄色背景 #fffde7
                                    c.setForeground(new Color(255, 193, 7));
                                    break;
                                case "即将临期":
                                    c.setBackground(new Color(227, 242, 253)); // 浅蓝色背景 #e3f2fd
                                    c.setForeground(new Color(33, 150, 243));
                                    break;
                                case "信息不完整":
                                    c.setBackground(new Color(245, 245, 245)); // 灰色背景
                                    c.setForeground(new Color(158, 158, 158));
                                    break;
                                default: // 正常
                                    c.setBackground(Color.WHITE);
                                    c.setForeground(Color.BLACK);
                                    break;
                            }
                        } else {
                            c.setBackground(Color.WHITE);
                            c.setForeground(Color.BLACK);
                        }

                        // 实现搜索结果高亮显示
                        if (expiringProductSearchField != null && value != null) {
                            String searchKeyword = expiringProductSearchField.getText().trim();
                            if (!searchKeyword.isEmpty() && (column == 0 || column == 1)) { // 商品编码或商品名称列
                                String cellValue = value.toString().toLowerCase();
                                if (cellValue.contains(searchKeyword.toLowerCase())) {
                                    // 高亮显示搜索匹配的文本
                                    setFont(getFont().deriveFont(Font.BOLD));
                                    if (!isSelected) {
                                        // 在原有背景色基础上增加高亮边框
                                        setBorder(BorderFactory.createCompoundBorder(
                                                BorderFactory.createLineBorder(new Color(255, 193, 7), 2),
                                                BorderFactory.createEmptyBorder(2, 4, 2, 4)));
                                    }
                                }
                            }
                        }

                    } catch (Exception e) {
                        c.setBackground(Color.WHITE);
                        c.setForeground(Color.BLACK);
                    }
                } else {
                    // 选中状态下的样式
                    c.setBackground(new Color(74, 144, 226, 100));
                    c.setForeground(Color.BLACK);
                }

                return c;
            }
        });

        // 中间面板：表格和商品详细信息
        JPanel centerPanel = createStyledPanel();
        centerPanel.setLayout(new BorderLayout(10, 0));

        // 表格滚动面板
        JScrollPane expiringScrollPane = new JScrollPane(expiringProductsTable);
        expiringScrollPane.setBorder(BorderFactory.createLineBorder(new Color(220, 220, 220)));
        expiringScrollPane.getViewport().setBackground(Color.WHITE);

        // 商品详细信息展示区域
        productDetailsArea = new JTextArea();
        productDetailsArea.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        productDetailsArea.setEditable(false);
        productDetailsArea.setBackground(new Color(248, 249, 250));
        productDetailsArea.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        productDetailsArea.setText("请选择商品查看详细信息");

        JScrollPane detailsScrollPane = new JScrollPane(productDetailsArea);
        detailsScrollPane.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createTitledBorder(
                        BorderFactory.createLineBorder(new Color(220, 220, 220)),
                        "商品详细信息",
                        0, 0,
                        new Font("Microsoft YaHei", Font.BOLD, 14),
                        new Color(52, 58, 64)),
                BorderFactory.createEmptyBorder(5, 5, 5, 5)));
        detailsScrollPane.setPreferredSize(new Dimension(300, 0));

        centerPanel.add(expiringScrollPane, BorderLayout.CENTER);
        centerPanel.add(detailsScrollPane, BorderLayout.EAST);

        expiringPanel.add(topPanel, BorderLayout.NORTH);
        expiringPanel.add(centerPanel, BorderLayout.CENTER);

        tabbedPane.addTab("临期申报", expiringPanel);
    }

    /**
     * 设置布局
     */
    private void setupLayout() {
        setLayout(new BorderLayout());
        setBackground(Color.WHITE);

        // 顶部信息栏
        JPanel topPanel = new JPanel(new BorderLayout());
        topPanel.setBackground(new Color(248, 249, 250));
        topPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(220, 220, 220)),
                BorderFactory.createEmptyBorder(15, 20, 15, 20)));

        JLabel titleLabel = new JLabel("超市管理系统 - 收银员工作台");
        titleLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 18));
        titleLabel.setForeground(new Color(52, 58, 64));

        topPanel.add(titleLabel, BorderLayout.WEST);
        topPanel.add(userInfoLabel, BorderLayout.EAST);

        // 底部状态栏
        JPanel statusPanel = new JPanel(new BorderLayout());
        statusPanel.setBackground(new Color(248, 249, 250));
        statusPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createMatteBorder(1, 0, 0, 0, new Color(220, 220, 220)),
                BorderFactory.createEmptyBorder(10, 20, 10, 20)));
        statusPanel.add(statusLabel, BorderLayout.WEST);

        JButton logoutButton = createStyledButton("注销", new Color(220, 53, 69));
        logoutButton.addActionListener(event -> logout());
        statusPanel.add(logoutButton, BorderLayout.EAST);

        // 主面板
        add(topPanel, BorderLayout.NORTH);
        add(tabbedPane, BorderLayout.CENTER);
        add(statusPanel, BorderLayout.SOUTH);
    }

    /**
     * 设置事件监听器
     */
    private void setupEventListeners() {
        // 商品查询
        productSearchButton.addActionListener(event -> searchProducts());
        productSearchField.addActionListener(event -> searchProducts());

        // 个人销售统计
        personalQueryButton.addActionListener(event -> queryPersonalSales());

        // 临期商品申报
        declareExpiringButton.addActionListener(event -> declareExpiringProducts());

        // 临期商品筛选和搜索
        setupExpiringProductsEventListeners();
    }

    /**
     * 设置窗口属性
     */
    private void setFrameProperties() {
        setTitle("超市管理系统 - 收银员");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(1200, 800);
        setLocationRelativeTo(null);
        setBackground(Color.WHITE);
        setMinimumSize(new Dimension(1000, 700));
        setExtendedState(JFrame.MAXIMIZED_BOTH);
    }

    /**
     * 加载初始数据
     */
    private void loadInitialData() {
        updateCheckoutInfo();
        loadAllProducts(); // 默认加载全部商品列表
        loadAllProductsWithExpiryInfo(); // 加载临期商品列表
        setStatus("系统已就绪，欢迎使用收银系统");
    }

    /**
     * 搜索商品（支持空关键词显示全部商品）
     */
    private void searchProducts() {
        String keyword = productSearchField.getText().trim();

        try {
            List<Product> products;

            if (keyword.isEmpty()) {
                // 如果没有关键词，显示全部商品
                products = productDAO.getAllProducts();
                setStatus("显示全部商品，共 " + products.size() + " 个商品");
            } else {
                // 有关键词时进行搜索
                products = productDAO.searchProducts(keyword);
                setStatus("搜索到 " + products.size() + " 个商品");
            }

            // 清空表格并重新加载数据
            productQueryTableModel.setRowCount(0);

            for (Product product : products) {
                Object[] row = {
                        product.getProductCode(),
                        product.getProductName(),
                        product.getCategoryName() != null ? product.getCategoryName() : "未分类",
                        product.getUnit(),
                        String.format("%.2f", product.getSalePrice()),
                        product.getCurrentStock() != null ? product.getCurrentStock().toString() : "0",
                        product.getStockStatus() != null ? product.getStockStatus() : "未知"
                };
                productQueryTableModel.addRow(row);
            }

        } catch (Exception e) {
            showError("查询商品失败：" + e.getMessage());
        }
    }

    /**
     * 加载全部商品列表
     */
    private void loadAllProducts() {
        try {
            List<Product> products = productDAO.getAllProducts();

            // 清空表格并加载数据
            productQueryTableModel.setRowCount(0);

            for (Product product : products) {
                Object[] row = {
                        product.getProductCode(),
                        product.getProductName(),
                        product.getCategoryName() != null ? product.getCategoryName() : "未分类",
                        product.getUnit(),
                        String.format("%.2f", product.getSalePrice()),
                        product.getCurrentStock() != null ? product.getCurrentStock().toString() : "0",
                        product.getStockStatus() != null ? product.getStockStatus() : "未知"
                };
                productQueryTableModel.addRow(row);
            }

            setStatus("已加载 " + products.size() + " 个商品");

        } catch (Exception e) {
            showError("加载商品列表失败：" + e.getMessage());
        }
    }

    /**
     * 查询个人销售统计
     */
    private void queryPersonalSales() {
        String period = personalPeriodComboBox.getSelectedItem().toString();

        try {
            personalSalesTableModel.setRowCount(0);

            // 根据选择的时间段计算日期范围
            LocalDate endDate = LocalDate.now();
            LocalDate startDate;

            switch (period) {
                case "今日":
                    startDate = endDate;
                    break;
                case "本周":
                    startDate = endDate.minusWeeks(1);
                    break;
                case "本月":
                    startDate = endDate.minusMonths(1);
                    break;
                default:
                    startDate = endDate;
                    break;
            }

            // 查询个人销售数据
            List<SalesOrder> orders = salesDAO.getSalesOrders(
                    currentUser.getId(),
                    Date.valueOf(startDate),
                    Date.valueOf(endDate));

            // 计算总金额
            BigDecimal totalSales = BigDecimal.ZERO;

            // 填充表格数据
            for (SalesOrder order : orders) {
                Object[] row = {
                        order.getOrderNo(),
                        order.getCreatedAt().toString().substring(0, 19), // 格式化时间
                        order.getItemCount(),
                        String.format("%.2f", order.getFinalAmount()),
                        translatePaymentMethod(order.getPaymentMethod()),
                        translateOrderStatus(order.getOrderStatus())
                };
                personalSalesTableModel.addRow(row);
                totalSales = totalSales.add(order.getFinalAmount());
            }

            personalTotalLabel.setText(String.format("个人销售总额: ¥%.2f", totalSales));
            setStatus(String.format("已查询%s个人销售统计，共%d个订单", period, orders.size()));

        } catch (Exception e) {
            showError("查询个人销售统计失败：" + e.getMessage());
        }
    }

    /**
     * 翻译支付方式
     */
    private String translatePaymentMethod(String paymentMethod) {
        switch (paymentMethod) {
            case "CASH":
                return "现金";
            case "CARD":
                return "刷卡";
            case "MOBILE":
                return "移动支付";
            default:
                return paymentMethod;
        }
    }

    /**
     * 翻译订单状态
     */
    private String translateOrderStatus(String orderStatus) {
        switch (orderStatus) {
            case "COMPLETED":
                return "已完成";
            case "PENDING":
                return "处理中";
            case "CANCELLED":
                return "已取消";
            default:
                return orderStatus;
        }
    }

    /**
     * 加载临期商品列表
     */
    private void loadExpiringProducts() {
        try {
            List<Product> expiringProducts = productDAO.getExpiringProducts();

            // 清空表格并重新加载数据
            expiringProductsTableModel.setRowCount(0);

            for (Product product : expiringProducts) {
                Object[] row = {
                        product.getProductCode(),
                        product.getProductName(),
                        product.getCategoryName() != null ? product.getCategoryName() : "未分类",
                        product.getShelfLifeDays(),
                        product.getRemainingDays(),
                        product.getCurrentStock() != null ? product.getCurrentStock().toString() : "0",
                        product.getStockStatus() != null ? product.getStockStatus() : "未知"
                };
                expiringProductsTableModel.addRow(row);
            }

            setStatus("已加载 " + expiringProducts.size() + " 个临期商品");

        } catch (Exception e) {
            showError("加载临期商品列表失败：" + e.getMessage());
        }
    }

    /**
     * 申报临期商品 - 增强版
     * 使用新的数据结构，预填充商品信息，根据过期状态自动设置建议处理方式
     * 修改申报成功处理逻辑，自动刷新商品列表
     */
    private void declareExpiringProducts() {
        int selectedRow = expiringProductsTable.getSelectedRow();
        if (selectedRow < 0) {
            showWarning("请先选择要申报的商品！");
            return;
        }

        try {
            // 获取选中商品的详细信息
            Product selectedProduct = getSelectedProductFromTable(selectedRow);
            if (selectedProduct == null) {
                showError("获取选中商品信息失败！");
                return;
            }

            // 检查商品是否已经申报过
            if (expiringProductDAO.isProductAlreadyReported(selectedProduct.getId())) {
                showWarning("该商品已经申报过临期，请勿重复申报！");
                return;
            }

            // 创建申报对话框
            showExpiringProductDeclarationDialog(selectedProduct);

        } catch (Exception e) {
            showError("申报临期商品失败：" + e.getMessage());
            logOperationError("申报临期商品", "未知商品", e);
        }
    }

    /**
     * 显示增强的临期商品申报对话框
     * 预填充商品信息，根据过期状态自动设置建议处理方式
     */
    private void showEnhancedDeclarationDialog(Product product) {
        // 创建对话框面板
        JPanel dialogPanel = new JPanel(new BorderLayout(10, 10));
        dialogPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        dialogPanel.setPreferredSize(new Dimension(600, 500));

        // 商品信息展示区域
        JPanel productInfoPanel = createProductInfoPanel(product);

        // 申报信息输入区域
        JPanel declarationPanel = createDeclarationInputPanel(product);

        // 组装对话框
        dialogPanel.add(productInfoPanel, BorderLayout.NORTH);
        dialogPanel.add(declarationPanel, BorderLayout.CENTER);

        // 显示对话框
        int result = JOptionPane.showConfirmDialog(
                this,
                dialogPanel,
                "申报临期商品 - " + product.getProductName(),
                JOptionPane.OK_CANCEL_OPTION,
                JOptionPane.PLAIN_MESSAGE);

        if (result == JOptionPane.OK_OPTION) {
            processDeclarationSubmission(product, declarationPanel);
        }
    }

    /**
     * 创建商品信息展示面板
     */
    private JPanel createProductInfoPanel(Product product) {
        JPanel panel = createStyledPanel();
        panel.setLayout(new GridBagLayout());
        panel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createTitledBorder(
                        BorderFactory.createLineBorder(new Color(220, 220, 220)),
                        "商品详细信息",
                        0, 0,
                        new Font("Microsoft YaHei", Font.BOLD, 14),
                        new Color(52, 58, 64)),
                BorderFactory.createEmptyBorder(15, 15, 15, 15)));

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(8, 10, 8, 10);
        gbc.anchor = GridBagConstraints.WEST;

        // 第一行：商品编码和名称
        gbc.gridx = 0;
        gbc.gridy = 0;
        panel.add(createInfoLabel("商品编码："), gbc);
        gbc.gridx = 1;
        panel.add(createInfoValue(product.getProductCode()), gbc);
        gbc.gridx = 2;
        panel.add(createInfoLabel("商品名称："), gbc);
        gbc.gridx = 3;
        panel.add(createInfoValue(product.getProductName()), gbc);

        // 第二行：类别和供应商
        gbc.gridx = 0;
        gbc.gridy = 1;
        panel.add(createInfoLabel("商品类别："), gbc);
        gbc.gridx = 1;
        panel.add(createInfoValue(product.getCategoryName()), gbc);
        gbc.gridx = 2;
        panel.add(createInfoLabel("供应商："), gbc);
        gbc.gridx = 3;
        panel.add(createInfoValue(product.getSupplierName()), gbc);

        // 第三行：出厂日期和保质期
        gbc.gridx = 0;
        gbc.gridy = 2;
        panel.add(createInfoLabel("出厂日期："), gbc);
        gbc.gridx = 1;
        panel.add(createInfoValue(product.getProductionDate() != null ? product.getProductionDate().toString() : "未知"),
                gbc);
        gbc.gridx = 2;
        panel.add(createInfoLabel("保质期："), gbc);
        gbc.gridx = 3;
        panel.add(createInfoValue(product.getShelfLifeDays() != null ? product.getShelfLifeDays() + " 天" : "未知"), gbc);

        // 第四行：过期日期和剩余天数
        gbc.gridx = 0;
        gbc.gridy = 3;
        panel.add(createInfoLabel("过期日期："), gbc);
        gbc.gridx = 1;
        panel.add(createInfoValue(product.getExpiryDate() != null ? product.getExpiryDate().toString() : "未知"), gbc);
        gbc.gridx = 2;
        panel.add(createInfoLabel("剩余天数："), gbc);
        gbc.gridx = 3;
        JLabel remainingDaysLabel = createInfoValue(
                product.getRemainingDays() != null ? product.getRemainingDays() + " 天" : "未知");
        // 根据剩余天数设置颜色
        if (product.getRemainingDays() != null) {
            if (product.getRemainingDays() <= 0) {
                remainingDaysLabel.setForeground(new Color(220, 53, 69)); // 红色
            } else if (product.getRemainingDays() <= 3) {
                remainingDaysLabel.setForeground(new Color(255, 152, 0)); // 橙色
            } else if (product.getRemainingDays() <= 7) {
                remainingDaysLabel.setForeground(new Color(255, 193, 7)); // 黄色
            }
        }
        panel.add(remainingDaysLabel, gbc);

        // 第五行：当前库存和过期状态
        gbc.gridx = 0;
        gbc.gridy = 4;
        panel.add(createInfoLabel("当前库存："), gbc);
        gbc.gridx = 1;
        panel.add(createInfoValue(product.getCurrentStock() != null ? product.getCurrentStock().toString() : "0"), gbc);
        gbc.gridx = 2;
        panel.add(createInfoLabel("过期状态："), gbc);
        gbc.gridx = 3;
        JLabel statusLabel = createInfoValue(product.getExpiryStatus() != null ? product.getExpiryStatus() : "未知");
        // 根据过期状态设置颜色
        setStatusLabelColor(statusLabel, product.getExpiryStatus());
        panel.add(statusLabel, gbc);

        return panel;
    }

    /**
     * 创建申报信息输入面板
     */
    private JPanel createDeclarationInputPanel(Product product) {
        JPanel panel = createStyledPanel();
        panel.setLayout(new GridBagLayout());
        panel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createTitledBorder(
                        BorderFactory.createLineBorder(new Color(220, 220, 220)),
                        "申报信息",
                        0, 0,
                        new Font("Microsoft YaHei", Font.BOLD, 14),
                        new Color(52, 58, 64)),
                BorderFactory.createEmptyBorder(15, 15, 15, 15)));

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10);
        gbc.anchor = GridBagConstraints.WEST;

        // 当前库存（预填充，可编辑）
        gbc.gridx = 0;
        gbc.gridy = 0;
        panel.add(createInfoLabel("申报库存："), gbc);
        gbc.gridx = 1;
        JTextField stockField = new JTextField(
                product.getCurrentStock() != null ? product.getCurrentStock().toString() : "0");
        stockField.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        stockField.setBorder(createModernBorder());
        stockField.setPreferredSize(new Dimension(250, 35));
        stockField.setName("stockField");
        panel.add(stockField, gbc);

        // 建议处理方式（根据过期状态自动设置）
        gbc.gridx = 0;
        gbc.gridy = 1;
        panel.add(createInfoLabel("处理方式："), gbc);
        gbc.gridx = 1;
        String[] actions = { "DISCOUNT", "DESTROY", "RETURN" };
        String[] actionLabels = { "折扣销售", "销毁处理", "退回供应商" };
        JComboBox<String> actionCombo = new JComboBox<>(actionLabels);
        actionCombo.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        actionCombo.setPreferredSize(new Dimension(250, 35));
        actionCombo.setName("actionCombo");

        // 根据过期状态自动设置建议处理方式
        String suggestedAction = getSuggestedActionByExpiryStatus(product.getExpiryStatus());
        for (int i = 0; i < actions.length; i++) {
            if (actions[i].equals(suggestedAction)) {
                actionCombo.setSelectedIndex(i);
                break;
            }
        }
        panel.add(actionCombo, gbc);

        // 折扣率（仅在选择折扣销售时启用）
        gbc.gridx = 0;
        gbc.gridy = 2;
        JLabel discountLabel = createInfoLabel("折扣率(%)：");
        panel.add(discountLabel, gbc);
        gbc.gridx = 1;
        JTextField discountField = new JTextField("20");
        discountField.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        discountField.setBorder(createModernBorder());
        discountField.setPreferredSize(new Dimension(250, 35));
        discountField.setName("discountField");
        panel.add(discountField, gbc);

        // 处理建议说明
        gbc.gridx = 2;
        gbc.gridy = 1;
        gbc.gridwidth = 2;
        JLabel suggestionLabel = new JLabel(getSuggestionByExpiryStatus(product.getExpiryStatus()));
        suggestionLabel.setFont(new Font("Microsoft YaHei", Font.ITALIC, 12));
        suggestionLabel.setForeground(new Color(108, 117, 125));
        panel.add(suggestionLabel, gbc);

        // 备注信息
        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.gridwidth = 1;
        panel.add(createInfoLabel("备注信息："), gbc);
        gbc.gridx = 1;
        gbc.gridwidth = 3;
        gbc.fill = GridBagConstraints.BOTH;
        JTextArea remarksArea = new JTextArea(3, 30);
        remarksArea.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        remarksArea.setBorder(createModernBorder());
        remarksArea.setName("remarksArea");
        remarksArea.setLineWrap(true);
        remarksArea.setWrapStyleWord(true);
        JScrollPane remarksScrollPane = new JScrollPane(remarksArea);
        remarksScrollPane.setPreferredSize(new Dimension(500, 80));
        panel.add(remarksScrollPane, gbc);

        // 添加处理方式变化监听器
        actionCombo.addActionListener(e -> {
            boolean isDiscount = actionCombo.getSelectedIndex() == 0; // 折扣销售
            discountField.setEnabled(isDiscount);
            discountLabel.setEnabled(isDiscount);
            if (!isDiscount) {
                discountField.setText("0");
            } else {
                discountField.setText("20");
            }
        });

        // 初始化折扣率字段状态
        boolean isDiscount = actionCombo.getSelectedIndex() == 0;
        discountField.setEnabled(isDiscount);
        discountLabel.setEnabled(isDiscount);

        return panel;
    }

    /**
     * 处理申报提交
     */
    private void processDeclarationSubmission(Product product, JPanel declarationPanel) {
        try {
            // 获取输入组件
            JTextField stockField = findComponentByName(declarationPanel, "stockField", JTextField.class);
            JComboBox<?> actionCombo = findComponentByName(declarationPanel, "actionCombo", JComboBox.class);
            JTextField discountField = findComponentByName(declarationPanel, "discountField", JTextField.class);
            JTextArea remarksArea = findComponentByName(declarationPanel, "remarksArea", JTextArea.class);

            // 数据验证和提取
            BigDecimal currentStock;
            try {
                currentStock = new BigDecimal(stockField.getText().trim());
                if (currentStock.compareTo(BigDecimal.ZERO) < 0) {
                    showWarning("库存数量不能为负数");
                    return;
                }
            } catch (NumberFormatException e) {
                showWarning("请输入有效的库存数量");
                return;
            }

            // 获取处理方式
            String[] actions = { "DISCOUNT", "DESTROY", "RETURN" };
            String suggestedAction = actions[actionCombo.getSelectedIndex()];

            // 获取折扣率
            BigDecimal discountRate = null;
            if ("DISCOUNT".equals(suggestedAction)) {
                try {
                    discountRate = new BigDecimal(discountField.getText().trim());
                    if (discountRate.compareTo(BigDecimal.ZERO) <= 0 ||
                            discountRate.compareTo(new BigDecimal("100")) > 0) {
                        showWarning("折扣率必须在0-100之间");
                        return;
                    }
                } catch (NumberFormatException e) {
                    showWarning("请输入有效的折扣率");
                    return;
                }
            }

            String remarks = remarksArea.getText().trim();

            // 创建申报对象
            ExpiringProduct expiringProduct = new ExpiringProduct();
            expiringProduct.setProductId(product.getId());
            expiringProduct.setReportedBy(currentUser.getId());
            expiringProduct.setCurrentStock(currentStock);
            expiringProduct.setExpiryDate(
                    product.getExpiryDate() != null ? new java.sql.Date(product.getExpiryDate().getTime())
                            : new java.sql.Date(System.currentTimeMillis()));
            expiringProduct.setSuggestedAction(suggestedAction);
            expiringProduct.setDiscountRate(discountRate);
            expiringProduct.setRemarks(remarks);
            expiringProduct.setStatus("PENDING");
            expiringProduct.setReportDate(new java.sql.Date(System.currentTimeMillis()));

            // 验证申报数据
            String validationError = expiringProduct.validateData();
            if (validationError != null) {
                showWarning("申报数据验证失败：" + validationError);
                return;
            }

            // 提交申报
            boolean success = expiringProductDAO.declareExpiringProduct(expiringProduct);

            if (success) {
                showInfo("临期商品申报成功！\n" +
                        "商品：" + product.getProductName() + "\n" +
                        "处理方式：" + expiringProduct.getSuggestedActionDescription() + "\n" +
                        "申报状态：待审批");

                // 刷新商品列表
                loadAllProductsWithExpiryInfo();
                setStatus("已申报临期商品：" + product.getProductName());
            } else {
                showError("申报失败，请重试");
            }

        } catch (Exception e) {
            showError("处理申报数据失败：" + e.getMessage());
        }
    }

    /**
     * 添加商品到购物车
     */
    private void addToCart() {
        String productCode = productCodeField.getText().trim();
        String quantityStr = quantityField.getText().trim();

        if (productCode.isEmpty()) {
            showWarning("请输入商品编码！");
            return;
        }

        BigDecimal quantity;
        try {
            quantity = new BigDecimal(quantityStr);
            if (quantity.compareTo(BigDecimal.ZERO) <= 0) {
                showWarning("数量必须大于0！");
                return;
            }
        } catch (NumberFormatException e) {
            showWarning("请输入正确的数量！");
            return;
        }

        try {
            Product product = findProductByCode(productCode);
            if (product == null) {
                showWarning("未找到该商品！");
                return;
            }

            // 检查库存
            if (product.getCurrentStock().compareTo(quantity) < 0) {
                showWarning("库存不足！当前库存：" + product.getCurrentStock());
                return;
            }

            // 检查购物车中是否已有该商品
            boolean found = false;
            for (int i = 0; i < cartItems.size(); i++) {
                CartItem item = cartItems.get(i);
                if (item.getProduct().getProductCode().equals(productCode)) {
                    // 更新数量
                    BigDecimal newQuantity = item.getQuantity().add(quantity);
                    if (product.getCurrentStock().compareTo(newQuantity) < 0) {
                        showWarning("库存不足！当前库存：" + product.getCurrentStock());
                        return;
                    }
                    item.setQuantity(newQuantity);
                    updateCartTableRow(i, item);
                    found = true;
                    break;
                }
            }

            if (!found) {
                // 添加新商品到购物车
                CartItem newItem = new CartItem(product, quantity);
                cartItems.add(newItem);
                addCartTableRow(newItem);
            }

            // 更新结算信息
            updateCheckoutInfo();

            // 清空输入框
            productCodeField.setText("");
            quantityField.setText("1");
            productCodeField.requestFocus();

            setStatus("商品已添加到购物车");

        } catch (Exception e) {
            showError("添加商品失败：" + e.getMessage());
        }
    }

    /**
     * 完成订单
     */
    private void completeOrder() {
        if (cartItems.isEmpty()) {
            showWarning("购物车为空，请先添加商品！");
            return;
        }

        try {
            // 计算最终金额
            BigDecimal totalAmount = BigDecimal.ZERO;
            for (CartItem item : cartItems) {
                BigDecimal subtotal = item.getProduct().getSalePrice().multiply(item.getQuantity());
                totalAmount = totalAmount.add(subtotal);
            }

            BigDecimal discountAmount = calculateDiscount(totalAmount);
            BigDecimal finalAmount = totalAmount.subtract(discountAmount);
            String paymentMethod = paymentMethodComboBox.getSelectedItem().toString();

            // 显示确认对话框
            String message = String.format(
                    "订单确认\n\n" +
                            "商品总额: ¥%.2f\n" +
                            "折扣金额: ¥%.2f\n" +
                            "应收金额: ¥%.2f\n" +
                            "支付方式: %s\n\n" +
                            "确定要完成此订单吗？",
                    totalAmount, discountAmount, finalAmount, paymentMethod);

            int confirm = JOptionPane.showConfirmDialog(this, message, "确认订单", JOptionPane.YES_NO_OPTION);

            if (confirm == JOptionPane.YES_OPTION) {
                // 1. 创建订单对象
                SalesOrder order = new SalesOrder();
                order.setCashierId(currentUser.getId());
                order.setOrderDate(new Date(System.currentTimeMillis()));
                order.setOrderTime(new Time(System.currentTimeMillis()));
                order.setOrderStatus("COMPLETED");

                // 转换支付方式为数据库枚举值
                String paymentMethodCode;
                switch (paymentMethod) {
                    case "刷卡":
                        paymentMethodCode = "CARD";
                        break;
                    case "移动支付":
                        paymentMethodCode = "MOBILE";
                        break;
                    case "现金":
                    default:
                        paymentMethodCode = "CASH";
                        break;
                }
                order.setPaymentMethod(paymentMethodCode);

                // 2. 创建订单明细列表
                List<SalesDetail> details = new ArrayList<>();
                for (CartItem item : cartItems) {
                    SalesDetail detail = new SalesDetail();
                    detail.setProductId(item.getProduct().getId());
                    detail.setQuantity(item.getQuantity());
                    detail.setUnitPrice(item.getProduct().getSalePrice());
                    // 促销逻辑暂未实现，折扣为0
                    detail.setDiscountAmount(BigDecimal.ZERO);
                    detail.setSubtotal(item.getProduct().getSalePrice().multiply(item.getQuantity()));
                    details.add(detail);
                }
                order.setSalesDetails(details);

                // 3. 设置订单总金额
                order.setTotalAmount(totalAmount);
                order.setDiscountAmount(discountAmount);
                order.setFinalAmount(finalAmount);

                // 4. 调用DAO保存订单
                SalesOrder createdOrder = salesDAO.createCompleteSalesOrder(order);

                if (createdOrder != null) {
                    showInfo(String.format("订单完成！\n订单编号: %s\n应收金额: ¥%.2f",
                            createdOrder.getOrderNo(), createdOrder.getFinalAmount()));
                    // 清空购物车并更新状态
                    clearCart();
                    setStatus("订单 " + createdOrder.getOrderNo() + " 已完成");
                    // 刷新个人销售统计
                    queryPersonalSales();
                } else {
                    showError("创建订单失败！\n可能是库存不足或其他原因，请重试或联系管理员。");
                }
            }

        } catch (Exception e) {
            showError("完成订单失败：" + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 取消当前订单
     */
    private void cancelOrder() {
        if (cartItems.isEmpty()) {
            showInfo("当前没有进行中的订单");
            return;
        }

        int confirm = JOptionPane.showConfirmDialog(this,
                "确定要取消当前订单吗？购物车中的所有商品将被清空。",
                "确认取消",
                JOptionPane.YES_NO_OPTION);

        if (confirm == JOptionPane.YES_OPTION) {
            clearCart();
            setStatus("订单已取消");
        }
    }

    /**
     * 清空购物车
     */
    private void clearCart() {
        cartItems.clear();
        cartTableModel.setRowCount(0);
        updateCheckoutInfo();
        productCodeField.setText("");
        quantityField.setText("1");
        productCodeField.requestFocus();
    }

    /**
     * 注销登录
     */
    private void logout() {
        int confirm = JOptionPane.showConfirmDialog(this, "确定要注销登录吗？", "确认注销",
                JOptionPane.YES_NO_OPTION);
        if (confirm == JOptionPane.YES_OPTION) {
            dispose();
            new LoginFrame().setVisible(true);
        }
    }

    /**
     * 设置状态信息
     */
    private void setStatus(String status) {
        statusLabel.setText(status);
    }

    /**
     * 显示错误信息
     */
    private void showError(String message) {
        JOptionPane.showMessageDialog(this, message, "错误", JOptionPane.ERROR_MESSAGE);
        setStatus("操作失败");
    }

    /**
     * 显示警告信息
     */
    private void showWarning(String message) {
        JOptionPane.showMessageDialog(this, message, "警告", JOptionPane.WARNING_MESSAGE);
    }

    /**
     * 显示信息提示
     */
    private void showInfo(String message) {
        JOptionPane.showMessageDialog(this, message, "提示", JOptionPane.INFORMATION_MESSAGE);
        setStatus(message);
    }

    /**
     * 购物车商品项
     */
    private static class CartItem {
        private Product product;
        private BigDecimal quantity;

        public CartItem(Product product, BigDecimal quantity) {
            this.product = product;
            this.quantity = quantity;
        }

        public Product getProduct() {
            return product;
        }

        public BigDecimal getQuantity() {
            return quantity;
        }

        public void setQuantity(BigDecimal quantity) {
            this.quantity = quantity;
        }
    }

    // ====================== UI 工具方法 ======================

    /**
     * 创建标准化面板
     */
    private JPanel createStyledPanel() {
        JPanel panel = new JPanel();
        panel.setBackground(Color.WHITE);
        return panel;
    }

    /**
     * 创建现代化按钮
     */
    private JButton createStyledButton(String text, Color backgroundColor) {
        JButton button = new JButton(text);
        button.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        button.setBackground(backgroundColor);
        button.setForeground(new Color(33, 37, 41)); // 统一使用深色文字
        button.setBorder(BorderFactory.createEmptyBorder(8, 16, 8, 16));
        button.setFocusPainted(false);
        button.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

        return button;
    }

    /**
     * 创建现代化边框
     */
    private javax.swing.border.Border createModernBorder() {
        return BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(220, 220, 220), 1),
                BorderFactory.createEmptyBorder(8, 12, 8, 12));
    }

    /**
     * 创建现代化表格
     */
    private JTable createStyledTable(DefaultTableModel model) {
        JTable table = new JTable(model);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        table.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        table.getTableHeader().setFont(new Font("Microsoft YaHei", Font.BOLD, 13));
        table.setRowHeight(35);

        // 设置表格样式
        table.setShowGrid(true);
        table.setGridColor(new Color(240, 240, 240));
        table.setSelectionBackground(new Color(74, 144, 226, 50));
        table.setSelectionForeground(new Color(52, 58, 64));

        // 设置表头样式
        table.getTableHeader().setBackground(new Color(248, 249, 250));
        table.getTableHeader().setForeground(new Color(52, 58, 64));
        table.getTableHeader().setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(220, 220, 220)));

        return table;
    }

    // ====================== 收银功能实现 ======================

    /**
     * 设置收银相关事件监听器
     */
    private void setupSalesEventListeners(JButton clearCartButton) {
        // 商品搜索
        searchProductButton.addActionListener(event -> searchAndAddProduct());
        productCodeField.addActionListener(event -> searchAndAddProduct());

        // 加入购物车
        addToCartButton.addActionListener(event -> addToCart());

        // 完成订单
        completeOrderButton.addActionListener(event -> completeOrder());

        // 取消订单
        cancelOrderButton.addActionListener(event -> cancelOrder());

        // 清空购物车
        clearCartButton.addActionListener(event -> clearCart());

        // 购物车双击删除商品
        cartTable.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                if (evt.getClickCount() == 2) {
                    removeFromCart();
                }
            }
        });
    }

    /**
     * 搜索并添加商品到购物车
     */
    private void searchAndAddProduct() {
        String productCode = productCodeField.getText().trim();
        if (productCode.isEmpty()) {
            showWarning("请输入商品编码！");
            return;
        }

        try {
            // 模拟商品查询 - 实际应调用ProductDAO
            Product product = findProductByCode(productCode);
            if (product != null) {
                // 自动设置商品信息并添加到购物车
                productCodeField.setText(product.getProductCode());
                addToCart();
            } else {
                showWarning("未找到商品编码为 " + productCode + " 的商品！");
                productCodeField.selectAll();
            }
        } catch (Exception e) {
            showError("搜索商品失败：" + e.getMessage());
        }
    }

    /**
     * 通过商品编码查找商品（调用数据库）
     */
    private Product findProductByCode(String productCode) {
        try {
            return productDAO.getProductByCode(productCode);
        } catch (Exception e) {
            showError("查找商品失败：" + e.getMessage());
            return null;
        }
    }

    /**
     * 添加购物车表格行
     */
    private void addCartTableRow(CartItem item) {
        Product product = item.getProduct();
        BigDecimal subtotal = product.getSalePrice().multiply(item.getQuantity());

        Object[] row = {
                product.getProductCode(),
                product.getProductName(),
                String.format("%.2f", product.getSalePrice()),
                item.getQuantity().toString(),
                String.format("%.2f", subtotal),
                "删除"
        };

        cartTableModel.addRow(row);
    }

    /**
     * 更新购物车表格行
     */
    private void updateCartTableRow(int rowIndex, CartItem item) {
        Product product = item.getProduct();
        BigDecimal subtotal = product.getSalePrice().multiply(item.getQuantity());

        cartTableModel.setValueAt(item.getQuantity().toString(), rowIndex, 3);
        cartTableModel.setValueAt(String.format("%.2f", subtotal), rowIndex, 4);
    }

    /**
     * 从购物车删除商品
     */
    private void removeFromCart() {
        int selectedRow = cartTable.getSelectedRow();
        if (selectedRow >= 0) {
            String productName = cartItems.get(selectedRow).getProduct().getProductName();

            int confirm = JOptionPane.showConfirmDialog(this,
                    "确定要从购物车中删除 " + productName + " 吗？",
                    "确认删除",
                    JOptionPane.YES_NO_OPTION);

            if (confirm == JOptionPane.YES_OPTION) {
                cartItems.remove(selectedRow);
                cartTableModel.removeRow(selectedRow);
                updateCheckoutInfo();
                setStatus("商品已从购物车中删除");
            }
        } else {
            showInfo("请选择要删除的商品");
        }
    }

    /**
     * 更新购物车商品数量
     */
    private void updateCartItemQuantity(int rowIndex) {
        if (rowIndex >= 0 && rowIndex < cartItems.size()) {
            try {
                String quantityStr = cartTableModel.getValueAt(rowIndex, 3).toString();
                BigDecimal newQuantity = new BigDecimal(quantityStr);

                if (newQuantity.compareTo(BigDecimal.ZERO) <= 0) {
                    showWarning("数量必须大于0！");
                    // 恢复原数量
                    cartTableModel.setValueAt(cartItems.get(rowIndex).getQuantity().toString(), rowIndex, 3);
                    return;
                }

                CartItem item = cartItems.get(rowIndex);
                Product product = item.getProduct();

                // 检查库存
                if (product.getCurrentStock().compareTo(newQuantity) < 0) {
                    showWarning("库存不足！当前库存：" + product.getCurrentStock());
                    // 恢复原数量
                    cartTableModel.setValueAt(item.getQuantity().toString(), rowIndex, 3);
                    return;
                }

                item.setQuantity(newQuantity);
                updateCartTableRow(rowIndex, item);
                updateCheckoutInfo();

            } catch (NumberFormatException e) {
                showWarning("请输入正确的数量！");
                // 恢复原数量
                cartTableModel.setValueAt(cartItems.get(rowIndex).getQuantity().toString(), rowIndex, 3);
            }
        }
    }

    /**
     * 更新结算信息
     */
    private void updateCheckoutInfo() {
        BigDecimal totalAmount = BigDecimal.ZERO;

        for (CartItem item : cartItems) {
            BigDecimal subtotal = item.getProduct().getSalePrice().multiply(item.getQuantity());
            totalAmount = totalAmount.add(subtotal);
        }

        // 计算折扣（这里可以添加促销逻辑）
        BigDecimal discountAmount = calculateDiscount(totalAmount);
        BigDecimal finalAmount = totalAmount.subtract(discountAmount);

        totalAmountLabel.setText(String.format("商品总额: ¥%.2f", totalAmount));
        discountLabel.setText(String.format("折扣金额: ¥%.2f", discountAmount));
        finalAmountLabel.setText(String.format("应收金额: ¥%.2f", finalAmount));
    }

    /**
     * 计算折扣金额（可以根据促销规则扩展）
     */
    private BigDecimal calculateDiscount(BigDecimal totalAmount) {
        // 简单的满减折扣：满100减5
        if (totalAmount.compareTo(new BigDecimal("100")) >= 0) {
            return new BigDecimal("5.00");
        }
        return BigDecimal.ZERO;
    }

    /**
     * 加载所有商品的完整过期信息
     * 实现自动过期状态计算和显示，按过期紧急程度排序显示
     */
    private void loadAllProductsWithExpiryInfo() {
        try {
            // 使用新的DAO方法获取所有商品的过期信息
            List<Product> products = expiringProductDAO.getAllProductsWithExpiryInfo();

            // 存储所有商品数据用于筛选和搜索
            allExpiringProducts = new ArrayList<>(products);
            filteredProducts = new ArrayList<>(products);

            // 更新表格显示
            updateExpiringProductsTable(products);

            // 更新状态栏
            setStatus("已加载 " + products.size() + " 个商品的过期信息");

        } catch (Exception e) {
            showError("加载商品过期信息失败：" + e.getMessage());

            // 空状态处理 - 显示空表格
            allExpiringProducts = new ArrayList<>();
            filteredProducts = new ArrayList<>();
            updateExpiringProductsTable(new ArrayList<>());
        }
    }

    /**
     * 设置临期商品筛选和搜索事件监听器
     */
    private void setupExpiringProductsEventListeners() {
        // 初始化搜索防抖动定时器
        searchTimer = new Timer(300, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                performFilterAndSearch();
                searchTimer.stop();
            }
        });
        searchTimer.setRepeats(false);

        // 过期状态筛选下拉框事件
        if (expiryStatusFilterComboBox != null) {
            expiryStatusFilterComboBox.addActionListener(event -> performFilterAndSearch());
        }

        // 实时搜索输入框事件 - 添加防抖动处理
        if (expiringProductSearchField != null) {
            expiringProductSearchField.getDocument().addDocumentListener(new DocumentListener() {
                @Override
                public void insertUpdate(DocumentEvent e) {
                    restartSearchTimer();
                }

                @Override
                public void removeUpdate(DocumentEvent e) {
                    restartSearchTimer();
                }

                @Override
                public void changedUpdate(DocumentEvent e) {
                    restartSearchTimer();
                }
            });
        }

        // 表格选择事件 - 显示商品详细信息
        if (expiringProductsTable != null) {
            expiringProductsTable.getSelectionModel().addListSelectionListener(event -> {
                if (!event.getValueIsAdjusting()) {
                    showSelectedProductDetails();
                }
            });
        }
    }

    /**
     * 重启搜索定时器（防抖动处理）
     */
    private void restartSearchTimer() {
        if (searchTimer != null) {
            searchTimer.restart();
        }
    }

    /**
     * 执行筛选和搜索
     */
    private void performFilterAndSearch() {
        if (allExpiringProducts == null) {
            return;
        }

        String selectedStatus = expiryStatusFilterComboBox != null
                ? expiryStatusFilterComboBox.getSelectedItem().toString()
                : "全部状态";
        String searchKeyword = expiringProductSearchField != null
                ? expiringProductSearchField.getText().trim().toLowerCase()
                : "";

        // 筛选商品
        filteredProducts = new ArrayList<>();

        for (Product product : allExpiringProducts) {
            // 按过期状态筛选
            boolean statusMatch = "全部状态".equals(selectedStatus) ||
                    (product.getExpiryStatus() != null && product.getExpiryStatus().equals(selectedStatus));

            // 按关键词搜索（商品名称和编码）
            boolean keywordMatch = searchKeyword.isEmpty() ||
                    (product.getProductName() != null && product.getProductName().toLowerCase().contains(searchKeyword))
                    ||
                    (product.getProductCode() != null
                            && product.getProductCode().toLowerCase().contains(searchKeyword));

            if (statusMatch && keywordMatch) {
                filteredProducts.add(product);
            }
        }

        // 更新表格显示
        updateExpiringProductsTable(filteredProducts);

        // 更新状态栏
        String statusMessage = String.format("显示 %d 个商品", filteredProducts.size());
        if (!"全部状态".equals(selectedStatus)) {
            statusMessage += "（状态：" + selectedStatus + "）";
        }
        if (!searchKeyword.isEmpty()) {
            statusMessage += "（搜索：" + searchKeyword + "）";
        }
        setStatus(statusMessage);
    }

    /**
     * 清除筛选条件和搜索
     */
    private void clearFiltersAndSearch() {
        // 重置筛选条件
        if (expiryStatusFilterComboBox != null) {
            expiryStatusFilterComboBox.setSelectedIndex(0); // 选择"全部状态"
        }

        // 清空搜索框
        if (expiringProductSearchField != null) {
            expiringProductSearchField.setText("");
        }

        // 重新显示所有商品
        if (allExpiringProducts != null) {
            updateExpiringProductsTable(allExpiringProducts);
            setStatus("已清除筛选条件，显示全部 " + allExpiringProducts.size() + " 个商品");
        }
    }

    /**
     * 显示选中商品的详细信息
     */
    private void showSelectedProductDetails() {
        int selectedRow = expiringProductsTable.getSelectedRow();
        if (selectedRow >= 0 && filteredProducts != null && selectedRow < filteredProducts.size()) {
            Product product = filteredProducts.get(selectedRow);

            StringBuilder details = new StringBuilder();
            details.append("商品详细信息\n");
            details.append("═══════════════════\n\n");
            details.append("商品编码：").append(product.getProductCode() != null ? product.getProductCode() : "未知")
                    .append("\n");
            details.append("商品名称：").append(product.getProductName() != null ? product.getProductName() : "未知商品")
                    .append("\n");
            details.append("商品类别：").append(product.getCategoryName() != null ? product.getCategoryName() : "未分类")
                    .append("\n");
            details.append("供应商：").append(product.getSupplierName() != null ? product.getSupplierName() : "未知供应商")
                    .append("\n\n");

            details.append("保质期信息\n");
            details.append("───────────────────\n");
            details.append("出厂日期：")
                    .append(product.getProductionDate() != null ? product.getProductionDate().toString() : "未知")
                    .append("\n");
            details.append("保质期：").append(product.getShelfLifeDays() != null ? product.getShelfLifeDays() + " 天" : "未知")
                    .append("\n");
            details.append("过期日期：").append(product.getExpiryDate() != null ? product.getExpiryDate().toString() : "未知")
                    .append("\n");
            details.append("剩余天数：")
                    .append(product.getRemainingDays() != null ? product.getRemainingDays() + " 天" : "未知").append("\n");
            details.append("过期状态：").append(product.getExpiryStatus() != null ? product.getExpiryStatus() : "未知")
                    .append("\n\n");

            details.append("库存信息\n");
            details.append("───────────────────\n");
            details.append("当前库存：")
                    .append(product.getCurrentStock() != null ? product.getCurrentStock().toString() : "0")
                    .append("\n");
            details.append("库存状态：").append(product.getStockStatus() != null ? product.getStockStatus() : "未知")
                    .append("\n\n");

            // 根据过期状态给出建议
            String suggestion = getSuggestionByExpiryStatus(product.getExpiryStatus());
            if (suggestion != null) {
                details.append("处理建议\n");
                details.append("───────────────────\n");
                details.append(suggestion);
            }

            if (productDetailsArea != null) {
                productDetailsArea.setText(details.toString());
                productDetailsArea.setCaretPosition(0); // 滚动到顶部
            }
        } else {
            if (productDetailsArea != null) {
                productDetailsArea.setText("请选择商品查看详细信息");
            }
        }
    }

    /**
     * 获取选中商品的详细信息
     */
    private Product getSelectedProductFromTable(int selectedRow) {
        if (filteredProducts == null || selectedRow < 0 || selectedRow >= filteredProducts.size()) {
            return null;
        }
        return filteredProducts.get(selectedRow);
    }

    /**
     * 根据过期状态自动设置建议处理方式
     */
    private String getSuggestedActionByExpiryStatus(String expiryStatus) {
        if (expiryStatus == null) {
            return "DISCOUNT";
        }

        switch (expiryStatus) {
            case "已过期":
                return "DESTROY"; // 已过期建议销毁
            case "即将过期":
                return "DISCOUNT"; // 即将过期建议折扣销售
            case "临期商品":
                return "DISCOUNT"; // 临期商品建议折扣销售
            case "即将临期":
                return "DISCOUNT"; // 即将临期建议折扣销售
            case "信息不完整":
                return "RETURN"; // 信息不完整建议退回供应商
            default:
                return "DISCOUNT"; // 默认折扣销售
        }
    }

    /**
     * 根据过期状态获取处理建议
     */
    private String getSuggestionByExpiryStatus(String expiryStatus) {
        if (expiryStatus == null) {
            return "建议进行折扣销售处理";
        }

        switch (expiryStatus) {
            case "已过期":
                return "商品已过期，建议销毁处理，确保食品安全";
            case "即将过期":
                return "商品即将过期，建议立即折扣销售";
            case "临期商品":
                return "商品临近过期，建议适当折扣销售";
            case "即将临期":
                return "商品即将临期，可考虑小幅折扣销售";
            case "信息不完整":
                return "商品信息不完整，建议退回供应商核实";
            case "正常":
                return "商品状态正常，可正常销售";
            default:
                return "请根据实际情况选择合适的处理方式";
        }
    }

    /**
     * 创建信息标签
     */
    private JLabel createInfoLabel(String text) {
        JLabel label = new JLabel(text);
        label.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        label.setForeground(new Color(73, 80, 87));
        return label;
    }

    /**
     * 创建信息值标签
     */
    private JLabel createInfoValue(String text) {
        JLabel label = new JLabel(text != null ? text : "未知");
        label.setFont(new Font("Microsoft YaHei", Font.BOLD, 14));
        label.setForeground(new Color(52, 58, 64));
        return label;
    }

    /**
     * 根据过期状态设置标签颜色
     */
    private void setStatusLabelColor(JLabel label, String expiryStatus) {
        if (expiryStatus == null) {
            return;
        }

        switch (expiryStatus) {
            case "已过期":
                label.setForeground(new Color(220, 53, 69)); // 红色
                break;
            case "即将过期":
                label.setForeground(new Color(255, 152, 0)); // 橙色
                break;
            case "临期商品":
                label.setForeground(new Color(255, 193, 7)); // 黄色
                break;
            case "即将临期":
                label.setForeground(new Color(33, 150, 243)); // 蓝色
                break;
            case "信息不完整":
                label.setForeground(new Color(158, 158, 158)); // 灰色
                break;
            default:
                label.setForeground(new Color(40, 167, 69)); // 绿色（正常）
                break;
        }
    }

    /**
     * 根据名称查找组件
     */
    @SuppressWarnings("unchecked")
    private <T> T findComponentByName(Container container, String name, Class<T> type) {
        for (Component component : container.getComponents()) {
            if (name.equals(component.getName()) && type.isInstance(component)) {
                return (T) component;
            }
            if (component instanceof Container) {
                T found = findComponentByName((Container) component, name, type);
                if (found != null) {
                    return found;
                }
            }
        }
        return null;
    }

    /**
     * 更新临期商品表格显示
     * 包含所有必要的商品信息，实现按过期紧急程度排序显示
     */
    private void updateExpiringProductsTable(List<Product> products) {
        // 清空表格
        if (expiringProductsTableModel != null) {
            expiringProductsTableModel.setRowCount(0);
        }

        // 空状态处理
        if (products.isEmpty()) {
            // 如果表格存在，显示空状态
            if (productDetailsArea != null) {
                productDetailsArea.setText("暂无符合条件的商品\n\n请尝试：\n- 调整筛选条件\n- 修改搜索关键词\n- 点击\"清除筛选\"查看全部商品");
            }
            return;
        }

        // 按过期紧急程度排序显示商品
        // 剩余天数少的排在前面，已过期的优先显示
        products.sort((p1, p2) -> {
            Integer days1 = p1.getRemainingDays();
            Integer days2 = p2.getRemainingDays();

            // 处理null值：null值排在最后
            if (days1 == null && days2 == null)
                return 0;
            if (days1 == null)
                return 1;
            if (days2 == null)
                return -1;

            // 按剩余天数升序排列（紧急的在前）
            return Integer.compare(days1, days2);
        });

        // 添加表格数据填充逻辑，包含所有必要的商品信息
        if (expiringProductsTableModel != null) {
            for (Product product : products) {
                Object[] row = {
                        product.getProductCode() != null ? product.getProductCode() : "未知",
                        product.getProductName() != null ? product.getProductName() : "未知商品",
                        product.getCategoryName() != null ? product.getCategoryName() : "未分类",
                        product.getSupplierName() != null ? product.getSupplierName() : "未知供应商",
                        product.getProductionDate() != null ? product.getProductionDate().toString() : "未知",
                        product.getShelfLifeDays() != null ? product.getShelfLifeDays().toString() : "未知",
                        product.getExpiryDate() != null ? product.getExpiryDate().toString() : "未知",
                        product.getRemainingDays() != null ? product.getRemainingDays().toString() : "未知",
                        product.getCurrentStock() != null ? product.getCurrentStock().toString() : "0",
                        product.getExpiryStatus() != null ? product.getExpiryStatus() : "未知"
                };
                expiringProductsTableModel.addRow(row);
            }
        }

        // 清空详细信息显示
        if (productDetailsArea != null && products.size() > 0) {
            productDetailsArea.setText("请选择商品查看详细信息");
        }
    }

    /**
     * 显示临期商品申报对话框
     * 预填充商品的当前库存和建议处理方式，根据过期状态自动设置建议处理方式
     */
    private void showExpiringProductDeclarationDialog(Product product) {
        JDialog dialog = new JDialog(this, "申报临期商品", true);
        dialog.setSize(700, 900);
        dialog.setLocationRelativeTo(this);
        dialog.setLayout(new BorderLayout());

        // 主面板
        JPanel mainPanel = createStyledPanel();
        mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 商品信息展示
        JPanel productInfoPanel = createStyledPanel();
        productInfoPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createTitledBorder(
                        BorderFactory.createLineBorder(new Color(220, 220, 220)),
                        "商品信息",
                        0, 0,
                        new Font("Microsoft YaHei", Font.BOLD, 14),
                        new Color(52, 58, 64)),
                BorderFactory.createEmptyBorder(15, 15, 15, 15)));
        productInfoPanel.setLayout(new GridBagLayout());

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(8, 8, 8, 8);
        gbc.anchor = GridBagConstraints.WEST;

        // 添加商品详细信息显示
        addProductInfoRow(productInfoPanel, gbc, 0, "商品编码：", product.getProductCode());
        addProductInfoRow(productInfoPanel, gbc, 1, "商品名称：", product.getProductName());
        addProductInfoRow(productInfoPanel, gbc, 2, "商品类别：", product.getCategoryName());
        addProductInfoRow(productInfoPanel, gbc, 3, "供应商：", product.getSupplierName());
        addProductInfoRow(productInfoPanel, gbc, 4, "过期日期：",
                product.getExpiryDate() != null ? product.getExpiryDate().toString() : "未知");
        addProductInfoRow(productInfoPanel, gbc, 5, "剩余天数：",
                product.getRemainingDays() != null ? product.getRemainingDays() + " 天" : "未知");

        // 过期状态用颜色标识
        JLabel statusLabel = new JLabel(product.getExpiryStatus() != null ? product.getExpiryStatus() : "未知");
        setStatusLabelColor(statusLabel, product.getExpiryStatus());
        statusLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 14));
        gbc.gridx = 0;
        gbc.gridy = 6;
        productInfoPanel.add(new JLabel("过期状态："), gbc);
        gbc.gridx = 1;
        productInfoPanel.add(statusLabel, gbc);

        // 申报信息输入
        JPanel declarationPanel = createStyledPanel();
        declarationPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createTitledBorder(
                        BorderFactory.createLineBorder(new Color(220, 220, 220)),
                        "申报信息",
                        0, 0,
                        new Font("Microsoft YaHei", Font.BOLD, 14),
                        new Color(52, 58, 64)),
                BorderFactory.createEmptyBorder(15, 15, 15, 15)));
        declarationPanel.setLayout(new GridBagLayout());

        // 当前库存（预填充）
        gbc.gridx = 0;
        gbc.gridy = 0;
        declarationPanel.add(new JLabel("当前库存："), gbc);
        JTextField stockField = new JTextField(
                product.getCurrentStock() != null ? product.getCurrentStock().toString() : "0");
        stockField.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        stockField.setBorder(createModernBorder());
        stockField.setPreferredSize(new Dimension(250, 35));
        gbc.gridx = 1;
        declarationPanel.add(stockField, gbc);

        // 建议处理方式（根据过期状态自动设置）
        gbc.gridx = 0;
        gbc.gridy = 1;
        declarationPanel.add(new JLabel("处理方式："), gbc);
        String[] actions = { "折扣销售", "销毁处理", "退回供应商" };
        JComboBox<String> actionComboBox = new JComboBox<>(actions);
        actionComboBox.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        actionComboBox.setPreferredSize(new Dimension(250, 35));

        // 根据过期状态自动设置建议处理方式
        String suggestedAction = getSuggestedActionByExpiryStatus(product.getExpiryStatus());
        switch (suggestedAction) {
            case "DESTROY":
                actionComboBox.setSelectedItem("销毁处理");
                break;
            case "RETURN":
                actionComboBox.setSelectedItem("退回供应商");
                break;
            default:
                actionComboBox.setSelectedItem("折扣销售");
                break;
        }
        gbc.gridx = 1;
        declarationPanel.add(actionComboBox, gbc);

        // 折扣率（仅在选择折扣销售时启用）
        gbc.gridx = 0;
        gbc.gridy = 2;
        JLabel discountLabel = new JLabel("折扣率(%)：");
        declarationPanel.add(discountLabel, gbc);
        JTextField discountField = new JTextField("10");
        discountField.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        discountField.setBorder(createModernBorder());
        discountField.setPreferredSize(new Dimension(250, 35));
        gbc.gridx = 1;
        declarationPanel.add(discountField, gbc);

        // 备注
        gbc.gridx = 0;
        gbc.gridy = 3;
        declarationPanel.add(new JLabel("备注："), gbc);
        JTextArea remarksArea = new JTextArea(3, 25);
        remarksArea.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        remarksArea.setBorder(createModernBorder());
        remarksArea.setLineWrap(true);
        remarksArea.setWrapStyleWord(true);
        JScrollPane remarksScrollPane = new JScrollPane(remarksArea);
        remarksScrollPane.setPreferredSize(new Dimension(250, 80));
        gbc.gridx = 1;
        declarationPanel.add(remarksScrollPane, gbc);

        // 处理方式变化时启用/禁用折扣率输入
        actionComboBox.addActionListener(e -> {
            boolean isDiscount = "折扣销售".equals(actionComboBox.getSelectedItem());
            discountField.setEnabled(isDiscount);
            discountLabel.setEnabled(isDiscount);
        });

        // 初始状态设置
        boolean isDiscount = "折扣销售".equals(actionComboBox.getSelectedItem());
        discountField.setEnabled(isDiscount);
        discountLabel.setEnabled(isDiscount);

        // 按钮面板
        JPanel buttonPanel = createStyledPanel();
        buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 15, 10));

        JButton confirmButton = createStyledButton("确认申报", new Color(40, 167, 69));
        JButton cancelButton = createStyledButton("取消", new Color(108, 117, 125));

        buttonPanel.add(confirmButton);
        buttonPanel.add(cancelButton);

        // 事件处理
        confirmButton.addActionListener(e -> {
            if (processExpiringProductDeclaration(dialog, product, stockField, actionComboBox,
                    discountField, remarksArea)) {
                dialog.dispose();
            }
        });

        cancelButton.addActionListener(e -> dialog.dispose());

        // 组装对话框
        mainPanel.add(productInfoPanel);
        mainPanel.add(Box.createVerticalStrut(15));
        mainPanel.add(declarationPanel);

        dialog.add(mainPanel, BorderLayout.CENTER);
        dialog.add(buttonPanel, BorderLayout.SOUTH);

        dialog.setVisible(true);
    }

    /**
     * 添加商品信息行到面板
     */
    private void addProductInfoRow(JPanel panel, GridBagConstraints gbc, int row, String label, String value) {
        gbc.gridx = 0;
        gbc.gridy = row;
        panel.add(new JLabel(label), gbc);

        JLabel valueLabel = new JLabel(value != null ? value : "未知");
        valueLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 14));
        valueLabel.setForeground(new Color(52, 58, 64));
        gbc.gridx = 1;
        panel.add(valueLabel, gbc);
    }

    /**
     * 处理临期商品申报
     * 实现申报数据验证和错误提示
     */
    private boolean processExpiringProductDeclaration(JDialog dialog, Product product,
            JTextField stockField, JComboBox<String> actionComboBox,
            JTextField discountField, JTextArea remarksArea) {

        try {
            // 验证输入数据
            BigDecimal currentStock;
            try {
                currentStock = new BigDecimal(stockField.getText().trim());
                if (currentStock.compareTo(BigDecimal.ZERO) < 0) {
                    showWarning("库存数量不能为负数！");
                    return false;
                }
            } catch (NumberFormatException e) {
                showWarning("请输入正确的库存数量！");
                return false;
            }

            String selectedAction = actionComboBox.getSelectedItem().toString();
            String actionCode;
            switch (selectedAction) {
                case "折扣销售":
                    actionCode = "DISCOUNT";
                    break;
                case "销毁处理":
                    actionCode = "DESTROY";
                    break;
                case "退回供应商":
                    actionCode = "RETURN";
                    break;
                default:
                    actionCode = "DISCOUNT";
                    break;
            }

            BigDecimal discountRate = null;
            if ("DISCOUNT".equals(actionCode)) {
                try {
                    discountRate = new BigDecimal(discountField.getText().trim());
                    if (discountRate.compareTo(BigDecimal.ZERO) <= 0 ||
                            discountRate.compareTo(new BigDecimal("100")) > 0) {
                        showWarning("折扣率必须在0-100之间！");
                        return false;
                    }
                } catch (NumberFormatException e) {
                    showWarning("请输入正确的折扣率！");
                    return false;
                }
            }

            String remarks = remarksArea.getText().trim();

            // 创建申报对象
            ExpiringProduct expiringProduct = new ExpiringProduct();
            expiringProduct.setProductId(product.getId());
            expiringProduct.setReportedBy(currentUser.getId());
            expiringProduct.setCurrentStock(currentStock);
            expiringProduct.setExpiryDate(
                    product.getExpiryDate() != null ? new java.sql.Date(product.getExpiryDate().getTime())
                            : new java.sql.Date(System.currentTimeMillis()));
            expiringProduct.setSuggestedAction(actionCode);
            expiringProduct.setDiscountRate(discountRate);
            expiringProduct.setRemarks(remarks);
            expiringProduct.setReportDate(new java.sql.Date(System.currentTimeMillis()));
            expiringProduct.setStatus("PENDING");

            // 验证申报数据
            String validationError = expiringProduct.validateData();
            if (validationError != null) {
                showWarning("申报数据验证失败：" + validationError);
                return false;
            }

            // 提交申报
            boolean success = expiringProductDAO.declareExpiringProduct(expiringProduct);

            if (success) {
                // 申报成功后的界面更新处理
                handleDeclarationSuccess(product, expiringProduct);
                return true;
            } else {
                showError("申报失败，请重试！");
                return false;
            }

        } catch (Exception e) {
            showError("申报过程中发生错误：" + e.getMessage());
            logOperationError("申报临期商品", product.getProductName(), e);
            return false;
        }
    }

    /**
     * 处理申报成功后的界面更新
     * 自动刷新商品列表，添加成功消息显示和状态更新，实现申报记录的状态跟踪
     */
    private void handleDeclarationSuccess(Product product, ExpiringProduct expiringProduct) {
        // 显示成功消息
        String message = String.format(
                "临期商品申报成功！\n\n" +
                        "商品：%s\n" +
                        "处理方式：%s\n" +
                        "申报状态：%s\n" +
                        "申报时间：%s",
                product.getProductName(),
                expiringProduct.getSuggestedActionDescription(),
                expiringProduct.getStatusDescription(),
                expiringProduct.getReportDate().toString());

        showSuccess(message);

        // 自动刷新商品列表
        SwingUtilities.invokeLater(() -> {
            try {
                // 重新加载商品数据
                loadAllProductsWithExpiryInfo();

                // 更新状态栏显示成功信息
                setStatus(String.format("成功申报临期商品：%s（申报ID：%d）",
                        product.getProductName(),
                        expiringProduct.getId() > 0 ? expiringProduct.getId() : 0));

                // 清空商品详细信息显示区域
                if (productDetailsArea != null) {
                    productDetailsArea.setText("申报成功！请选择其他商品查看详细信息");
                }

            } catch (Exception e) {
                showError("刷新商品列表失败：" + e.getMessage());
            }
        });

        // 添加操作日志记录功能
        logOperationSuccess("申报临期商品", product.getProductName(), expiringProduct);
    }

    /**
     * 记录操作成功日志
     */
    private void logOperationSuccess(String operation, String productName, ExpiringProduct expiringProduct) {
        try {
            String logMessage = String.format(
                    "[%s] 用户：%s，操作：%s，商品：%s，处理方式：%s，申报状态：%s",
                    new java.util.Date().toString(),
                    currentUser.getRealName(),
                    operation,
                    productName,
                    expiringProduct.getSuggestedActionDescription(),
                    expiringProduct.getStatusDescription());

            // 这里可以写入日志文件或数据库
            System.out.println("操作日志：" + logMessage);

        } catch (Exception e) {
            System.err.println("记录操作日志失败：" + e.getMessage());
        }
    }

    /**
     * 记录操作错误日志
     */
    private void logOperationError(String operation, String productName, Exception error) {
        try {
            String logMessage = String.format(
                    "[%s] 用户：%s，操作：%s，商品：%s，错误：%s",
                    new java.util.Date().toString(),
                    currentUser.getRealName(),
                    operation,
                    productName,
                    error.getMessage());

            // 这里可以写入日志文件或数据库
            System.err.println("错误日志：" + logMessage);

        } catch (Exception e) {
            System.err.println("记录错误日志失败：" + e.getMessage());
        }
    }

    // ====================== 消息显示工具方法 ======================

    /**
     * 显示成功消息
     */
    private void showSuccess(String message) {
        JOptionPane.showMessageDialog(this, message, "操作成功", JOptionPane.INFORMATION_MESSAGE);
    }
}